package com.hotel.api.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hotel.api.common.RedisOperator;
import com.hotel.api.entity.AdminNotice;
import com.hotel.api.entity.Lost;
import com.hotel.api.entity.User;
import com.hotel.api.entity.UserRole;
import com.hotel.api.service.AdminService;
import com.hotel.api.service.UserService;
import com.hotel.api.utils.JSONResult;
import com.hotel.api.utils.JsonUtils;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.kafka.KafkaProperties;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/admin")
@Transactional
public class AdminController {

    @Autowired
    AdminService adminService;

    @Autowired
    UserService userService;

    @Autowired
    RedisOperator redisOperator;



    /**
     * 登录
     *
     * @param phoneNumber
     * @param password
     * @return
     */
    @ApiOperation("管理员登录")
    @PostMapping("/adminLogin")

    public JSONResult adminLogin(String phoneNumber, String password, HttpServletRequest httpServletRequest) {

        if (StringUtils.isBlank(phoneNumber)) {
            System.out.println("手机号不能为空");
            return JSONResult.errorMsg("手机号不能为空");
        }
        if (StringUtils.isBlank(password)) {
            System.out.println("密码不能为空");
            return JSONResult.errorMsg("密码不能为空");
        }
        User user = userService.selectByPhoneNumber(phoneNumber);

        if (user == null) {
            System.out.println("用户不存在");
            return JSONResult.errorMsg("用户不存在");
        }
        if (password.equals(user.getPassword())) {
            if (adminService.adminLogin(user.getId())==null){
                return JSONResult.errorMsg("你没有权限登录");
            }
            user.setPassword("******");
            System.out.println("管理员登录成功");
            HttpSession httpSession = httpServletRequest.getSession();
            httpSession.setAttribute("UserInfo", JsonUtils.objectToJson(user));
            httpSession.setAttribute("loginUserId", user.getId());
            redisOperator.set("loginUser:" + user.getId(), httpSession.getId());
            return JSONResult.build(200, "欢迎管理员："+user.getName(), user);
        }
        System.out.println("密码错误");
        return JSONResult.errorMsg("密码错误");


    }


    /**
     * 发布失物招领
     *
     * @return
     */
    @ApiOperation("发布失物招领")
    @PostMapping("/publishLost")
    public JSONResult publishLost(Lost lost, Part file) {
        if (lost.getTitle().isEmpty() || lost.getDescription().isEmpty()) {
            return JSONResult.errorMsg("标题和描述不能为空");
        }
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // new Date()为获取当前系统时间，也可使用当前时间戳
        String date = df.format(new Date());
        lost.setCreateTime(date);
//        lost.setState(0);
        lost.setDelState((byte) 0);
//        if (file != null) {
//            //设置图片
//            String fileName = file.getSubmittedFileName();
//            try {
//                file.write(fileName);
//                lost.setPhoto(fileName);
//            } catch (Exception e) {
//                e.printStackTrace();
//                return JSONResult.errorMsg("发布失败");
//            }
//        }
        adminService.addLost(lost);
        return JSONResult.ok("发布成功");
    }


    /**
     * 认领失物,0为未认领，1为已认领
     */
    @ApiOperation("认领失物/删除失物招领/更改失物招领信息")
    @PostMapping("/updateLost")
    public JSONResult updateLost(Lost lost) {
        //根据id查询该订单是否存在
        Lost lost1 = adminService.findLostById(lost.getId());
        if (lost1 == null) {
            return JSONResult.errorMsg("没有此订单");
        } else {
            //设置日期格式
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // new Date()为获取当前系统时间
            String date = df.format(new Date());
            //判断是更改操作还是删除操作
            if (lost.getTitle() != null || lost.getDescription() != null) {
                adminService.updateLost(lost);
                return JSONResult.ok("更新成功");
            }
            if (lost.getDelState() == null) {
                if (lost.getState() == 1) {
                    adminService.updateLost(lost);
                    return JSONResult.ok("撤回用户认领成功");
                } else if (lost.getState() == 0) {
                    lost.setFinishTime(date);
                    adminService.updateLost(lost);
                    return JSONResult.ok("认领失物成功");
                } else if (lost.getDelState() == 1) {
                    adminService.updateLost(lost);
                    return JSONResult.ok("删除成功");
                }
            }
        }

        return JSONResult.errorMsg("操作失败");
    }


    /**
     * 查看所有失物
     */
    @ApiOperation("查看所有失物")
    @PostMapping("/lostlist")
    public JSONResult showLostList(@RequestParam(value = "page", defaultValue = "1", required = false) Integer page,
                                   @RequestParam(value = "limit", defaultValue = "10", required = false) Integer limit) {
        PageHelper.startPage(page, limit);
        List<Lost> list = adminService.selectAllLost();
        PageInfo<Lost> pageInfo = new PageInfo<>(list);
        System.out.println("查看所有失物");
        return JSONResult.build(200, "失物招领信息", pageInfo);
    }


    /**
     * 查看所有公告信息
     *
     * @return
     */
    @ApiOperation("查看所有公告信息")
    @PostMapping("/allNotice")
    public JSONResult showNoticeList(@RequestParam(value = "page", defaultValue = "1", required = false) Integer page,
                                     @RequestParam(value = "limit", defaultValue = "10", required = false) Integer limit) {
        PageHelper.startPage(page, limit);
        List<AdminNotice> noticList = adminService.getNoticList();
        PageInfo<AdminNotice> pageInfo = new PageInfo<>(noticList);
        System.out.println("查询所有公告成功");
        return JSONResult.build(200, "查询成功", pageInfo);
    }

    /**
     * 发布公告
     *
     * @param adminNotice
     * @param file
     * @return
     * @throws ParseException
     */
    @ApiOperation("发布公告")
    @PostMapping("/publishNotice")
    public JSONResult addNotice(AdminNotice adminNotice, Part file) {
        if (adminNotice.getTheam() == null || adminNotice.getDescription() == null) {
            return JSONResult.errorMsg("标题和描述不能为空");
        }
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // new Date()为获取当前系统时间，也可使用当前时间戳
        String date = df.format(new Date());
        adminNotice.setCreateTime(date);
        adminNotice.setDelState((byte) 0);
        //设置图片
//        String fileName = file.getSubmittedFileName();
//        try {
//            file.write(fileName);
//            adminNotice.setPhoto(fileName);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return JSONResult.errorMsg("发布失败");
//        }
        adminService.addNotice(adminNotice);
        return JSONResult.build(200, "发布公告成功", adminNotice);
    }

    /**
     * 删除公告
     *
     * @param adminNotice
     * @return
     */

    @ApiOperation("删除公告/更新公告")
    @PostMapping("/updateNotice")
    public JSONResult updateNotice(AdminNotice adminNotice) {
        try {
            if (adminNotice.getDelState() == 1) {
                adminService.updateNotice(adminNotice);
                return JSONResult.ok("删除公告成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        adminService.updateNotice(adminNotice);
        return JSONResult.ok("更新成功");
    }


}